package dao

import (
	"webgame/internal/model"
	"webgame/pkg/utils"

	"github.com/go-redis/redis"
	"github.com/topfreegames/pitaya/v2/component"
	"github.com/topfreegames/pitaya/v2/logger"
	"xorm.io/xorm"
)

type BaseDao struct {
	component.Base
	engine      *xorm.Engine
	redisClient *redis.Client
}

func (b *BaseDao) Init() {

	enginer, err := utils.ManagerUtil.GetDbEnginer()
	if err != nil {
		logger.Log.Errorf("BaseDao Init failed,error:%s", err.Error())
		return
	}
	b.engine = enginer

	rdClient, err := utils.ManagerUtil.GetRedisClient()
	if err != nil {
		logger.Log.Errorf("BaseDao Init failed,error:%s", err.Error())
		return
	}
	b.redisClient = rdClient
}

// DB
func (b *BaseDao) Get(data model.DBData) (ds model.DBData, err error) {
	ds, err = b.GetByDB(data)
	if err != nil {
		logger.Log.Errorf("[BaseDao] Get failed,error:%s", err.Error())
		return nil, err
	}

	return ds, nil
}

func (b *BaseDao) Update(data model.DBData, query string, args ...interface{}) error {
	_, err := b.UpdateDB(data, query, args...)
	if err != nil {
		logger.Log.Errorf("[BaseDao] Update failed,error:%s", err.Error())
		return err
	}

	return nil
}

func (b *BaseDao) GetByDB(data model.DBData) (model.DBData, error) {
	obj, err := b.engine.Get(data)
	if err != nil {
		logger.Log.Errorf("[BaseDao] GetByDb failed,error:%s", err.Error())
		return nil, err
	}

	if !obj {
		return nil, nil
	}

	return data, nil
}

func (b *BaseDao) UpdateDB(data model.DBData, query string, args ...interface{}) (int64, error) {
	r, err := b.engine.Where(query, args...).Update(data)
	if err != nil {
		logger.Log.Errorf("Update failed,error:%s", err.Error())
		return 0, err
	}

	return r, nil
}

func (b *BaseDao) DeleteDb(data model.DBData) error {
	_, err := b.engine.Delete(data)
	if err != nil {
		logger.Log.Errorf("[BaseDao] DeleteDb failed,error:%s", err.Error())
		return err
	}
	return nil
}

//Redis
